package com.yuan.studemo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuan.studemo.ExceptionHandler.ServiceException;
import com.yuan.studemo.common.Constants;
import com.yuan.studemo.controller.dto.StuinfoDto;
import com.yuan.studemo.entity.Stuinfo;
import com.yuan.studemo.mapper.StuinfoMapper;
import com.yuan.studemo.service.IStuinfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuan.studemo.utils.TokenUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 学生 服务实现类
 * </p>
 *
 * @author Yuan
 * @since 2022-05-19
 */
@Service
public class StuinfoServiceImpl extends ServiceImpl<StuinfoMapper, Stuinfo> implements IStuinfoService {

    private static final Log LOG = Log.get();

    @Override
    public StuinfoDto login(StuinfoDto stuinfoDto) {
        QueryWrapper<Stuinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stuId", stuinfoDto.getStuId());
        queryWrapper.eq("password", stuinfoDto.getPassword());
        Stuinfo one;
        // 处理异常情况
        try {
            one = getOne(queryWrapper);//从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        if (one != null) {
            BeanUtil.copyProperties(one, stuinfoDto, true);
            //设置token
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            stuinfoDto.setToken(token);
            return stuinfoDto;
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }
    }

}
